using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using star_questionnair.Models;
using star_questionnair.Models.Enum;
using star_questionnair.Services;
using star_questionnair.Services.impl;
using star_questionnair.Utilities;

namespace star_questionnair.Services.impl;

public class ChoiceAnalysisService
{
    private readonly IQuestionService _questionService;
    private readonly IAnswerService _answerService;
    private readonly IOptionService _optionService;
    private readonly IHistoryService _historyService;

    public ChoiceAnalysisService(
        IQuestionService questionService,
        IAnswerService answerService,
        IOptionService optionService,
        IHistoryService historyService)
    {
        _questionService = questionService;
        _answerService = answerService;
        _optionService = optionService;
        _historyService = historyService;
    }

    public async Task<Dictionary<string, int>> GetSelectionCountsAsync(int questionId)
    {
        var question = await _questionService.GetQuestionByIdAsync(questionId);

        // 判断是否为选择题类型
        if (!QuestionEnumExtensions.IsChoiceType(question.Type))
        {
            return null;
        }

        // 获取该问题的所有选项
        var options = _historyService.GetOptionsByQuestionId(questionId);

        // 初始化选项选取数的字典
        var optionCountMap = options.ToDictionary(option => option.Id, option => 0);

        // 获取该问题的所有答案
        var answers =  _historyService.GetAnswersByQuestionId(questionId);

        // 计算每个选项的选取次数
        foreach (var answer in answers)
        {
            var selectedOptionIds = answer.Content.Split(",");
            foreach (var selectedOptionId in selectedOptionIds)
            {
                int optionId = int.Parse(selectedOptionId.Trim());
                optionCountMap[optionId]++;
            }
        }

        // 转换为所需的返回格式
        var selectionCounts = options.ToDictionary(
            option => option.Content,
            option => optionCountMap[option.Id]);

        return selectionCounts;
    }
}